<script setup lang="ts">
import RoomStatus from './components/RoomStatus.vue'
import RoomAction from './components/RoomAction.vue'
import RoomMessage from './components/RoomMessage.vue'
import { onMounted, onUnmounted, ref, nextTick, provide } from 'vue'
import { io } from 'socket.io-client'
import type { Socket } from 'socket.io-client'
import { baseURL } from '@/utils/request'
import { useUserStore } from '@/stores'
import { useRoute } from 'vue-router'
import type { Message, TimeMessages } from '@/types/root'
import { MsgType, OrderType } from '@/enums'
import type { ConsultOrderItem, Image } from '@/types/consult'
import { getConsultOlderDetail } from '@/services/consult'
import dayjs from 'dayjs'
import { showToast } from 'vant'

const store = useUserStore()
const route = useRoute()
// 建立socked链接
let socket: Socket
const list = ref<Message[]>([])
onMounted(() => {
  socket = io(baseURL, {
    // 身份认证
    auth: {
      token: `Bearer ${store.user?.token}`
    },
    // 订单id
    query: {
      orderId: route.query.orderId
    }
  })

  // 链接成功
  socket.on('connect', () => {
    list.value = []
    console.log('链接成功')
  })
  // 关闭
  socket.on('disconnect', () => {
    console.log('断开成功')
  })
  socket.on('error', (error) => {
    console.log('错误', error)
  })

  // 接收消息
  socket.on('chatMsgList', ({ data }: { data: TimeMessages[] }) => {
    const arr: Message[] = []
    data.forEach((item, i) => {
      // 记录消息第一次的时间，作为下一次获取数据的时间
      if (i === 0) time.value = item.createTime
      arr.push({
        id: item.createTime,
        msgType: MsgType.Notify,
        createTime: item.createTime,
        msg: {
          content: item.createTime
        }
      })
      arr.push(...item.items)
    })
    list.value.unshift(...arr)
    // 关闭上拉刷新加载
    loading.value = false
    if (!data.length) {
      showToast('没有更多聊天记录')
    }
    // 第一次滚动到底部
    nextTick(() => {
      if (initalMsg.value) {
        socket.emit('updateMsgStatus', arr[arr.length - 1].id)
        window.scrollTo(0, document.body.scrollHeight)
        initalMsg.value = false
      }
    })
  })
  // 链接成功 订单状态改变
  socket.on('statusChange', async () => {
    const res = await getConsultOlderDetail(route.query.orderId as string)
    consult.value = res.data
  })
  // 接收消息
  socket.on('receiveChatMsg', async (msg: Message) => {
    list.value.push(msg)
    socket.emit('updateMsgStatus', msg.id)
    await nextTick()
    window.scrollTo(0, document.body.scrollHeight)
  })
})

onUnmounted(() => {
  socket.close()
})

const consult = ref<ConsultOrderItem>()
onMounted(async () => {
  const res = await getConsultOlderDetail(route.query.orderId as string)
  consult.value = res.data
})

const sendText = (text: string) => {
  socket.emit('sendChatMsg', {
    from: store.user?.id,
    to: consult.value?.docInfo?.id,
    msgType: MsgType.MsgText,
    msg: {
      content: text
    }
  })
}

// 发送图片信息
const sendImage = (img: Image) => {
  socket.emit('sendChatMsg', {
    from: store.user?.id,
    to: consult.value?.docInfo?.id,
    msgType: MsgType.MsgText,
    msg: {
      picture: img
    }
  })
}

// 加载更多
const initalMsg = ref(true)
const loading = ref(false)
// 初始化时间
const time = ref(dayjs().format('YYYY-MM-DD HH:mm:ss'))
const onRefresh = () => {
  socket.emit('getChatMsgList', 20, time.value, route.query.orderId)
}

provide('consult', consult)
const complateEva = (score: number) => {
  const item = list.value.find((item) => item.msgType === MsgType.CardEvaForm)
  if (item) {
    item.msg.evaluateDoc = { score }
    item.msgType = MsgType.CardEva
  }
}
provide('complateEva', complateEva)
</script>

<template>
  <div class="room-page">
    <cp-nav-bar title="问诊室" />
    <room-status
      :status="consult?.status"
      :countdown="consult?.countdown"
    ></room-status>
    <van-pull-refresh v-model="loading" @refresh="onRefresh">
      <room-message :list="list"></room-message>
    </van-pull-refresh>
    <room-action
      :disabled="consult?.status !== OrderType.ConsultChat"
      @send-text="sendText"
      @send-image="sendImage"
    ></room-action>
  </div>
</template>

<style lang="scss" scoped>
.room-page {
  padding-top: 90px;
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);
  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
</style>
